package com.spzx.common.rabbit.service;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送消息
     *
     * @param exchange   交换机
     * @param routingKey 路由键
     * @param message    消息
     */
    public boolean sendMessage(String exchange, String routingKey, Object message) {
        GuiguCorrelationData guiguCorrelationData = new GuiguCorrelationData();
        String uuid="mq:"+ UUID.randomUUID().toString().replace("-","");
        guiguCorrelationData.setId(uuid);
        guiguCorrelationData.setMessage(message);
        guiguCorrelationData.setExchange(exchange);
        guiguCorrelationData.setRoutingKey(routingKey);


        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(guiguCorrelationData),10, TimeUnit.MINUTES);
        rabbitTemplate.convertAndSend(exchange,routingKey,message,guiguCorrelationData);
        return true;
    }

    public Boolean sendDelayMessage(String exchange, String routingDelay, String message, int delayTime) {
        GuiguCorrelationData guiguCorrelationData = new GuiguCorrelationData();
        String uuid="mq:"+UUID.randomUUID().toString().replaceAll("-","");
        guiguCorrelationData.setId(uuid);
        guiguCorrelationData.setMessage(message);
        guiguCorrelationData.setExchange(exchange);
        guiguCorrelationData.setRoutingKey(routingDelay);
        guiguCorrelationData.setDelay(true);
        guiguCorrelationData.setDelayTime(delayTime);
        //将相关消息存入redis中
        redisTemplate.opsForValue().set(uuid,JSON.toJSONString(guiguCorrelationData),10,TimeUnit.MINUTES);
        //将相关消息封装到发送消息方法中
        rabbitTemplate.convertAndSend(exchange,routingDelay,message,message1 -> {
            message1.getMessageProperties().setDelay(delayTime*1000);
            return message1;
        },guiguCorrelationData);
        return true;
    }
}